<template>
  <div class="vulnerability-list-container">
    <div class="page-header">
      <div class="page-actions">
        <el-button type="primary" icon="Plus" @click="handleAdd"
          >新增漏洞</el-button
        >
        <el-button icon="Upload" @click="handleUpload">导入</el-button>
        <el-button
          icon="download"
          @click="handleExport"
          :disabled="!selectedRows.length"
          >导出</el-button
        >
        <el-button
          icon="Delete"
          type="danger"
          plain
          @click="handleBatchDelete"
          :disabled="!selectedRows.length"
          >批量删除</el-button
        >
      </div>
    </div>

    <!-- 搜索表单 -->
    <search-form
      v-model="searchForm"
      :loading="loading"
      @search="handleSearch"
      @reset="handleReset"
    >
      <el-form-item label="漏洞名称">
        <el-input
          v-model="searchForm.title"
          placeholder="请输入漏洞名称"
          clearable
        />
      </el-form-item>
      <el-form-item label="产品类型">
        <el-select
          v-model="searchForm.product_type"
          placeholder="请选择产品类型"
          clearable
        >
          <el-option
            v-for="(value, key) in product_type"
            :key="value"
            :label="value"
            :value="value"
          />
        </el-select>
      </el-form-item>      
      <el-form-item label="漏洞类型">
        <el-select
          v-model="searchForm.vuln_type"
          placeholder="请选择漏洞类型"
          clearable
        >
          <el-option
            v-for="item in vulnTypeList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="危害等级">
        <el-select
          v-model="searchForm.level"
          placeholder="请选择危害等级"
          clearable
        >
          <el-option
            v-for="(value, key) in level_list"
            :key="key"
            :label="key"
            :value="key"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="POC/EXP">
        <el-select
          style="width: 200px"
          v-model="searchForm.is_exist_poc_exp"
          placeholder="查询POC/EXP是否存在"
          clearable
        >
          <el-option label="是" value="1" />
          <el-option label="否" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="漏洞描述">
        <el-input
        style="width: 400px;"
          v-model="searchForm.description"
          type="textarea"
          :rows="3"
          placeholder="请输入漏洞描述"
        />
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          @change="handleDateRangeChange"
        />
      </el-form-item>
      <el-form-item label="漏洞来源">
        <el-select
          v-model="searchForm.source"
          placeholder="请选择漏洞来源"
          clearable
        >
          <el-option
            v-for="item in sourceList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据源">
      <el-select
          v-model="searchForm.is_standard"
          placeholder="数据源"
          clearable
        >
          <el-option label="预备库" :value="0" />
          <el-option label="标准库" :value="1" />
          <el-option label="全部" :value="2" />
        </el-select>
        </el-form-item>
      <!-- 匹配配置区域 -->
      <el-form-item>
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-right: 100px;
          "
        >
          <el-radio-group
            v-model="searchForm.mode"
            @change="handleMatchingTypeChange"
          >
            <el-radio-button :label="0">模糊匹配</el-radio-button>
            <el-radio-button :label="1">精确匹配</el-radio-button>
          </el-radio-group>
        </div>
      </el-form-item>
    </search-form>
    <div class="result-header">
      <div class="result-title">匹配结果</div>
      <div class="page-actions">
        <el-button
          icon="Download"
          @click="handleExportResult"
          :disabled="!selectedMatchRows.length"
          plain
          type="primary"
          >导出报告</el-button
        >
        <div class="result-summary">
          共找到 {{ total }} 个匹配漏洞，当前显示
          {{ matchingResult.length }} 条
        </div>
      </div>
    </div>
    <VulnTable
      :tableData="tableData"
      :loading="loading"
      @selection-change="handleSelectionChange"
    >
      <template #optSlot>
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              icon="View"
              @click="handleViewDetails(row)"
              >查看详情</el-button
            >
            <el-button type="primary" link icon="Edit" @click="handleEdit(row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              link
              icon="Delete"
              @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </template>
    </VulnTable>

    <div v-if="total > 0" class="pagination-container">
      <el-pagination
        background
        v-model:current-page="page"
        v-model:page-size="limit"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handlePagination"
        @current-change="handlePagination"
      />
    </div>

    <!-- 引入漏洞弹窗组件 -->
    <vulnerability-dialog      
      v-model:visible="dialogVisible"
      :type="dialogType"
      :vulnerability-data="currentVulnerability"
      :loading="submitLoading"
      @submit="submitForm"
      :vulnTypeList="vulnTypeList"
      :sourceList="sourceList"
      :levelList="level_list"
    />
    <!-- 引入上传弹窗组件 -->
    <upload-vuln-dialog v-model:visible="uploadVisible" />

    <!-- 漏洞详情弹窗 -->
    <VulnDetailDialog
      v-model="detailVisible"
      :vuln-data="currentVulnData"
      @closed="handleDetailClosed"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getVulnerabilityList,
  updateVulnerability,
  addVulnerability,
  deleteVulnerability,
  exportVulnerability,
  getProductList
} from "@/api/vulnerability";
import { getVulnMatchDetail } from "@/api/vulnMatch.js";
import { downloadFileFromResponse } from "@/utils/fileOpt.js";
import VulnerabilityDialog from "./components/VulnerabilityDialog.vue";
import VulnDetailDialog from "@/components/vulnDetailDialog/index.vue";
import UploadVulnDialog from "./components/UploadVulnDialog.vue";
import SearchForm from "@/components/SearchForm/index.vue";
import VulnTable from "@/components/vulnTable/index.vue";
import { exportJson } from "@/utils/fileOpt";

import { useCommonStore } from "@/stores/common";
const store = useCommonStore();

// 状态变量
const loading = ref(false);
const submitLoading = ref(false);
const page = ref(1);
const limit = ref(10);
const total = ref(0);
const tableData = ref([]);
const selectedRows = ref([]);
const selectedMatchRows = ref([]);
const dialogVisible = ref(false);
const uploadVisible = ref(false);
const dialogType = ref("add");
const currentVulnerability = ref({});
const vulnTypeList = computed(() => store.vulnTypeList);
const sourceList = computed(() => store.sourceList);
const level_list = ref({
  低: "warning",
  中: "warning",
  高: "danger",
  严重: "danger",
});
const product_type = ref([]);// 产品类型
// 获取产品类型
function getProcuctType (){
  getProductList().then(res=>{
    if(res.code === 200){
      product_type.value = res.data.map(item=>{
        return item;
      })
    }
  })
}
// 详情弹窗相关
const detailVisible = ref(false);
const currentVulnData = ref({});
const matchingResult = ref([]);
// 搜索表单
const searchForm = reactive({
  mode: 0,
  is_standard: 1
});

// 日期范围
const dateRange = ref([]);
// 处理匹配类型变更
const handleMatchingTypeChange = (type) => {
  assetForm.mode = type;
};
// 导出结果
const handleExportResult = async () => {
  try {
    if (!matchingResult.value.length) {
      ElMessage.warning("没有可导出的数据");
      return;
    }

    const data = {
      id_list: selectedMatchRows.value,
    };
    const res = await getVulnMatchDetail(data);

    // 下载文件
    downloadFileFromResponse(res);

    ElMessage.success("匹配结果导出成功");
  } catch (error) {
    console.error("导出失败:", error);
    ElMessage.error("匹配结果导出失败");
  }
};
// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page_index: page.value,
      page_size: limit.value,
      title: searchForm.title,
      vuln_type: searchForm.vuln_type,
      level: searchForm.level,
      start_time: searchForm.start_time,
      end_time: searchForm.end_time,
      is_exist_poc_exp: searchForm.is_exist_poc_exp,
      source: searchForm.source,
      description: searchForm.description,
      mode: searchForm.mode,
      is_standard: searchForm.is_standard,
      product_type: searchForm.product_type,
    };

    const res = await getVulnerabilityList(params);
    tableData.value = res.data || [];
    matchingResult.value = res.data || [];
    total.value = res.total_items || 0;
  } catch (error) {
    console.error("获取漏洞列表失败:", error);
    ElMessage.error("获取漏洞列表失败");
  } finally {
    loading.value = false;
  }
};
// 查看详情
const handleViewDetails = (row) => {
  currentVulnData.value = row;
  detailVisible.value = true;
};
// 详情弹窗关闭
const handleDetailClosed = () => {
  currentVulnData.value = {};
};

// 处理日期范围变化
const handleDateRangeChange = (val) => {
  if (val) {
    searchForm.start_time = val[0];
    searchForm.end_time = val[1];
  } else {
    searchForm.start_time = "";
    searchForm.end_time = "";
  }
};

// 处理搜索
const handleSearch = () => {
  page.value = 1;
  fetchData();
};

// 处理重置
const handleReset = () => {
  dateRange.value = [];
  Object.keys(searchForm).forEach((key) => {
    searchForm[key] = "";
  });
  searchForm.mode = 0;
  searchForm.is_standard = 1;
  handleSearch();
};

// 处理分页
const handlePagination = () => {
  fetchData();
};

// 处理选择行变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection;
  selectedMatchRows.value = selection.map((item) => item.id);
};

// 处理添加
const handleAdd = () => {
  dialogType.value = "add";
  currentVulnerability.value = {};
  dialogVisible.value = true;
};

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = "edit";
  currentVulnerability.value = {};
  currentVulnerability.value = { ...row };
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm("确定要删除该漏洞吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      await deleteVulnerability({
        id_list: [row.id],
      });
      ElMessage.success("删除成功");
      fetchData();
    } catch (error) {
      console.error("删除漏洞失败:", error);
      ElMessage.error("删除漏洞失败");
    }
  });
};

// 处理批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning("请选择要删除的漏洞");
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个漏洞吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  ).then(async () => {
    try {
      await deleteVulnerability({
        id_list: selectedRows.value.map((row) => row.id),
      });
      ElMessage.success("批量删除成功");
      fetchData();
    } catch (error) {
      console.error("批量删除漏洞失败:", error);
      ElMessage.error("批量删除漏洞失败");
    }
  });
};

// 处理导出
const handleExport = async () => {
  try {
    const idList =
      selectedRows.value.length > 0
        ? selectedRows.value.map((row) => row.id)
        : tableData.value.map((row) => row.id);
    let data = await exportVulnerability({ id_list: idList });
    console.log(data);

    exportJson(
      data,
      `漏洞信息id-${idList.join(",")}-${new Date().getTime()}.json`
    );
    ElMessage.success("导出成功");
  } catch (error) {
    console.error("导出漏洞失败:", error);
    ElMessage.error("导出漏洞失败");
  }
};

// 打开导入弹窗
const handleUpload = () => {
  uploadVisible.value = true;
};

// 提交表单
const submitForm = async (form) => {
  submitLoading.value = true;
  try {
    const formData = new FormData();
    for (const key in form) {
      switch (key) {
        case "vuln_references":
        console.log('vuln_references',form[key])
        if (form[key] && form[key].length > 0) {
            form[key].forEach(id => {
              formData.append(key, id);
            });
          }
          break;
        case "product_list":
        console.log('product_list',form[key])
        if (form[key] && form[key].length > 0) {
            form[key].forEach(id => {
              formData.append(key, id);
            });
          }
          break;
        case "delete_poc_list":
          // 仅在数组有数据时才添加到FormData
          if (form[key] && form[key].length > 0) {
            form[key].forEach(id => {
              formData.append(key, id);
            });
          }
          break;
        // case "poc_list":
        //   formData.append(key, JSON.stringify(form[key]));
        //   break;
        case "poc_files":
          for (let i = 0; i < form[key].length; i++) {
            formData.append(key, form[key][i]);
          }
          break;
        default:
          formData.append(key, form[key]);
          break;
      }
    }
    if (dialogType.value === "add") {
      await addVulnerability(formData);
    } else {
      await updateVulnerability(formData);
    }
    ElMessage.success(dialogType.value === "add" ? "添加成功" : "更新成功");
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    console.error("保存漏洞失败:", error);
    ElMessage.error("保存漏洞失败");
  } finally {
    submitLoading.value = false;
  }
};

// 格式化类型
const formatVulnType = (type) => {
  const typeMap = {
    rce: "RCE",
    "privilege-escalation": "权限提升",
    "auth-bypass": "认证绕过",
    "info-leak": "信息泄露",
  };
  return typeMap[type] || type;
};

// 获取标签类型
const getTagType = (level) => {
  return level_list.value[level] || "";
};

// 初始化
onMounted(() => {
  getProcuctType();
  fetchData();
});
</script>

<style lang="scss" scoped>
.vulnerability-list-container {
  padding: 20px;
  .page-actions {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 10px;
  }
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--text-color);
    }

    .page-actions {
      display: flex;
      gap: 10px;
    }
  }
  .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;

      .result-title {
        font-size: 16px;
        font-weight: bold;
      }

      .result-summary {
        margin: 0 20px;
        color: var(--text-color-secondary);
      }
    }
}
</style>
